package com.lyxedu.services.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyxedu.mapper.RoleMapper;
import com.lyxedu.mapper.RoleMenuMapper;
import com.lyxedu.mapper.UserMapper;
import com.lyxedu.pojo.Menu;
import com.lyxedu.pojo.Role;
import com.lyxedu.pojo.RoleMenu;
import com.lyxedu.pojo.User;
import com.lyxedu.services.MenuService;
import com.lyxedu.services.RoleService;
import com.lyxedu.services.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Resource
    private RoleMenuMapper roleMenuMapper;
    @Resource
    private MenuService menuService;
//    新增或者删除权限
    @Override
    public boolean saveOrUpdateUser(Role role) {
        if (role.getId() != null){
//            修改
            return updateById(role);
        }
        return save(role);
    }

//  修改或者新增角色权限
    @Transactional
    @Override
    public void saveRoleWithMenu(Integer roleId, List<Integer> menuIds) {
        roleMenuMapper.deleteRoleWithById(roleId);
        List<Integer> menuIdsCopy = CollUtil.newArrayList(menuIds);
        for (Integer menuId : menuIds) {
            Menu menu = menuService.getById(menuId);
            if (menu.getPid() != null && !menuIdsCopy.contains(menu.getPid())) { // 二级菜单 并且传过来的menuId数组里面没有它的父级id
                // 那么我们就得补上这个父级id
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(menu.getPid());
                roleMenuMapper.insert(roleMenu);
                menuIdsCopy.add(menu.getPid());
            }
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setMenuId(menuId);
            roleMenu.setRoleId(roleId);
            roleMenuMapper.insert(roleMenu);
        }
    }
}
